# -*- coding:utf-8 -*-  

# Contact with the author by :
# itech001@126.com
# www.cnblogs.com/itech

import os
import sys
import socket

import PyRRCommon

logger = PyRRCommon.PyRRLogger() 
# why output twice when using the below code 
#logger = PyRRCommon.PyRRLogger().instance()
    
def remote_running_client(host, port, cmd_or_scriptfn):
    '''
        this fuction is used to connect to the server,
        and excute cmd or script file in the server.
        
        host and port are used to connect to server.
        cmd_or_scriptfn is "-c:cmd" or "-sf:scriptfilename".
    '''

     # Create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Connect to server
    logger.debug("Connect to: " + host + ":"+ repr(port))
    sock.connect((host, port))

    # if the parameter is cmd, send cmd, and if the parameter is script file name,
    # read the script file and send the whole script to the server.
    # note: all line sent to the server must be end with os.linesep.
    t, v = PyRRCommon.is_cmd_or_scriptfn(cmd_or_scriptfn)
    sfname = ''
    cmd = ''
    if t == "cmd" :
        cmd = v
        logger.debug("Sent: %s" %cmd)
        sock.send(bytes(cmd + os.linesep,'utf-8'))
    elif t == "scriptfn":
        sfname = v
        if not os.path.exists(sfname):
            logger.error("The file %s is not exist." % sfname)
            exit()

        lines = PyRRCommon.read_file_lines(sfname)

        # the first line will be <ext|linenum>
        ext = os.path.splitext(sfname)[1]  
        firstline = "<" + ext + "|" + repr(len(lines)) + ">" + os.linesep
        logger.debug("Sent: %s" % firstline)
        sock.send(bytes(firstline,'utf-8'))
  
        for line in lines:
            if not line.endswith(bytes(os.linesep,'utf-8')) : 
                line += bytes(os.linesep,'utf-8')
            logger.debug("Sent: %s" % str(line,'utf-8'))
            sock.send(line)

    # Receive data from the server and shut down
    while True:
        received = sock.recv(1024)
        if len(received) < 1024 : 
            logger.debug("Received: %s" % str(received,'utf-8'))
            break
        
    # when cmd or script run finishs, close the connection.
    sock.close()
